package org.jcut.controller;

import java.util.List;
import java.util.UUID;

import javax.validation.Valid;

import org.jcut.bean.Collect;

import org.jcut.data.Data;
import org.jcut.service.CollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@RestController
@RequestMapping("/collect")
public class CollectController {
	@Autowired
	private Data data;
	@Autowired
	private CollectService service;
	/**
	 * @author 王征
	 * @param sid 摊点id
	 * @param uId 用户id
	 * 
	 * */
	@RequestMapping("/add")
	public Object add(@Valid Collect collect,Errors error) {
		List<ObjectError> e=error.getAllErrors();
		if(e.size()>0) {
			for(ObjectError ee:e) {
				data.setMyData(0,ee.getDefaultMessage(),0);	
			}
		}else {
			collect.setId(UUID.randomUUID().toString());
			int i=service.insert(collect);
			data.setMyData(i,i>0?"添加成功":"服务器异常",i);
		}
		
		return data;
	}
	/**
	 * @author 王征
	 * @param id 收藏的id
	 * 
	 * */
	@RequestMapping("/delete")
	public Object delete(String id,String uid) {
		int i=service.delect(id,uid);
		data.setMyData(i,i>0?"删除成功":"服务器异常", i);
		return data;
	}
	@RequestMapping("/check")
	public Object check(Collect collect) {
		long i=service.check(collect);
		if(i>0) {
			data.setData(0);
			data.setMsg("你已经添加");
			data.setStatus("0");
			
		}else {
			data.setData(1);
			data.setMsg("可以添加");
			data.setStatus("1");
		}
		return data;
	}
	@RequestMapping("/selectByUid")
	public Object selectByUid(String uId,@RequestParam(value="pageNum",required = false)String pageNum,@RequestParam(value="pageSize",required = false) String pageSize) {
		if ((pageNum != null && !("".equals(pageNum))) && (pageSize != null && !("".equals(pageSize)))) {
			PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
		}
		PageInfo<Collect> pageInfo = new PageInfo<>(service.selectByUid(uId));
		
		
		data.setMyData(1, "查询成功",pageInfo );
		return data;
	}
	@RequestMapping("/selectAll")
	public Object selectAll() {
		data.setMyData(1, "查询成功", service.selectAll());
		return data;
	}
}
